package com.smartguard.datasource;

import java.io.InputStream;
import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
import com.smartguard.util.XMLUtil;

public class MongoConnection {
	/**
	 * 数据库连接池
	 */
	private static MongoClient mongoClient = null;
	
	/**
	 * 数据库名
	 */
	private static String dbName = "";
	
	static{
		init();
	}
	
	/**
	 * 从数据库连接池中取出一个数据库连接
	 * @return
	 */
	public static DB getDB(){
		if(mongoClient != null){
			return mongoClient.getDB(dbName);
		}
		else return null;
	}
	
	/***
	 * MongoClient类加载时就初始化
	 */
	public static void init(){
		InputStream configInputStream = MongoConnection.class.getClassLoader().getResourceAsStream("mongo.xml");
		XMLUtil xmlUtil = XMLUtil.getXMLUtil(configInputStream);
		dbName = xmlUtil.getParam("dbName");
		String ip = xmlUtil.getParam("ip");
		String port = xmlUtil.getParam("port");
		
		try {
			mongoClient = new MongoClient(new ServerAddress(ip+":"+port));
		} catch (UnknownHostException e) {
			System.out.println("连接mongo连接池失败");
			e.printStackTrace();
		}
	}
	
}
